<template>
  <div class="avatar-upload">
    <el-upload
      class="avatar-uploader"
      :show-file-list="false"
      :before-upload="beforeAvatarUpload"
      :on-success="handleAvatarSuccess"
      :on-error="handleAvatarError"
      accept="image/*"
    >
      <img v-if="avatarUrl" :src="avatarUrl" class="avatar" />
      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>
    
    <div class="avatar-tips">
      <p>支持 JPG、PNG 格式，文件大小不超过 5MB，会自动压缩到 150x150</p>
    </div>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import request from '@/utils/request'

const props = defineProps({
  username: {
    type: String,
    required: true
  },
  currentAvatar: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['avatar-updated'])

const avatarUrl = ref(props.currentAvatar)

// 监听父组件传入的currentAvatar变化，自动同步到avatarUrl
watch(
  () => props.currentAvatar,
  (newVal) => {
    avatarUrl.value = newVal
  }
)

// 压缩图片
const compressImage = (file) => {
  return new Promise((resolve) => {
    console.log('开始压缩图片:', file.name, '大小:', file.size, '字节')
    
    const canvas = document.createElement('canvas')
    const ctx = canvas.getContext('2d')
    const img = new Image()
    
    img.onload = () => {
      // 设置最大尺寸
      const maxSize = 150 // 进一步减小尺寸
      let { width, height } = img
      
      console.log('原始图片尺寸:', width, 'x', height)
      
      // 等比例缩放
      if (width > height) {
        if (width > maxSize) {
          height = (height * maxSize) / width
          width = maxSize
        }
      } else {
        if (height > maxSize) {
          width = (width * maxSize) / height
          height = maxSize
        }
      }
      
      console.log('压缩后尺寸:', width, 'x', height)
      
      canvas.width = width
      canvas.height = height
      
      // 绘制图片
      ctx.drawImage(img, 0, 0, width, height)
      
      // 转换为base64，使用更低的质量
      const compressedDataUrl = canvas.toDataURL('image/jpeg', 0.5)
      const base64Data = compressedDataUrl.split(',')[1]
      
      console.log('压缩后数据长度:', base64Data.length, '字符')
      
      resolve(base64Data)
    }
    
    img.src = URL.createObjectURL(file)
  })
}

// 上传前验证
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isJPG && !isPNG) {
    ElMessage.error('头像只能是 JPG 或 PNG 格式!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('头像大小不能超过 5MB!')
    return false
  }
  
  // 读取文件并压缩
  return new Promise((resolve, reject) => {
    compressImage(file).then(base64Data => {
      uploadAvatar(base64Data, 'image/jpeg') // 统一转换为JPEG格式
      resolve(false) // 阻止默认上传行为
    }).catch(error => {
      reject(error)
    })
  })
}

// 上传头像
const uploadAvatar = async (base64Data, fileType) => {
  try {
    const response = await request.post('/user/uploadAvatar', {
      username: props.username,
      avatarData: base64Data,
      fileType: fileType
    })
    
    if (response.data.code === 200) {
      avatarUrl.value = response.data.data
      ElMessage.success('头像上传成功')
      emit('avatar-updated', avatarUrl.value)
    } else {
      ElMessage.error(response.data.message || '头像上传失败')
    }
  } catch (error) {
    console.error('头像上传失败:', error)
    ElMessage.error('头像上传失败')
  }
}

// 上传成功回调
const handleAvatarSuccess = (response) => {
  // 这里不会执行，因为我们阻止了默认上传行为
}

// 上传失败回调
const handleAvatarError = (error) => {
  console.error('头像上传错误:', error)
  ElMessage.error('头像上传失败')
}
</script>

<style scoped>
.avatar-upload {
  text-align: center;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 120px;
  height: 120px;
  margin: 0 auto;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
  line-height: 120px;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
  object-fit: cover;
}

.avatar-tips {
  margin-top: 10px;
  color: #666;
  font-size: 12px;
}
</style> 